#include "Character.h"

#include "Balloon.h"


Character::Character()
{
    maxVelocity = ccp(4.f, 4.f);
    maxAngularVelocity = 0.5f;
}

Character::~Character()
{

}

void Character::createAction()
{

}

void Character::changeState(unsigned char _state)
{

}

void Character::createBalloon()
{
    mBalloon = new Balloon();
    mBalloon->initGameObjectWith(handler, this);
    handler->addDynamicObject(mBalloon, sprite->getZOrder());
}

void Character::beginContact(b2Fixture *ownFixture, b2Fixture *otherFixture, b2Contact *contact)
{

}

void Character::endContact(b2Fixture *ownFixture, b2Fixture *otherFixture, b2Contact *contact)
{

}

void Character::removeObject()
{
    mBalloon = NULL;

    PhysicObject::removeObject();
}

void Character::characterFly(b2Vec2 _flyVector)
{
    if (_flyVector.x < 0) {
        direction = DIRECT_LEFT;
        this->sprite->setFlipX(true);
    }
    else if (_flyVector.x > 0) {
        direction = DIRECT_RIGHT;
        this->sprite->setFlipX(false);
    }

    // restrict high
    if (handler->worldSize.height - sprite->getPositionY() < 4 * sprite->getContentSize().height) {
        _flyVector = b2Vec2(_flyVector.x, 0);
    }
    // apply force
    if (mBalloon->isBalloon) {
        //mBalloon->physicBody->ApplyForceToCenter(b2Vec2(_flyVector.x * flyForce.x, _flyVector.y * flyForce.y));
        mBalloon->balloonFly(b2Vec2(_flyVector.x * flyForce.x, _flyVector.y * flyForce.y));
    } else {
        //mBalloon->physicBody->ApplyForceToCenter(b2Vec2(_flyVector.x * flyForce.x, 0));
        mBalloon->balloonFly(b2Vec2(_flyVector.x * flyForce.x, 0));
    }
}

void Character::update(float dt)
{
    if (!sprite || !physicBody) {
        return;
    }
    // restrict velocity
    if (physicBody->GetLinearVelocity().x > maxVelocity.x) {
        physicBody->SetLinearVelocity(b2Vec2(maxVelocity.x, physicBody->GetLinearVelocity().y));
    }
    else if (physicBody->GetLinearVelocity().x < -maxVelocity.x) {
        physicBody->SetLinearVelocity(b2Vec2(-maxVelocity.x, physicBody->GetLinearVelocity().y));
    }
    if (physicBody->GetLinearVelocity().y > maxVelocity.y) {
        physicBody->SetLinearVelocity(b2Vec2(physicBody->GetLinearVelocity().x, maxVelocity.y));
    }
    else if (physicBody->GetLinearVelocity().y < -maxVelocity.y) {
        physicBody->SetLinearVelocity(b2Vec2(physicBody->GetLinearVelocity().x, -maxVelocity.y));
    }

    // restrict angular velocity
    if (physicBody->GetAngularVelocity() > maxAngularVelocity) {
        physicBody->SetAngularVelocity(maxAngularVelocity);
    }
    else if (physicBody->GetAngularVelocity() < -maxAngularVelocity) {
        physicBody->SetAngularVelocity(-maxAngularVelocity);
    }

    PhysicObject::update(dt);
    sprite->setRotation(-CC_RADIANS_TO_DEGREES(physicBody->GetAngle()));
}
